<!-- 入库单信息详情界面 -->
<template>
    <!--基本信息-->
    <div class="white-container">
        <!--头部-->
        <div class="header-row">
            <h3 class="title">入库单号：{{ instockform.code }}</h3>
            <div class="btn-group">
                <el-button @click="ShowUpdate" v-if="['草稿', '待审核'].includes(instockform.status)">编辑</el-button>
                <el-button @click="ShowDelete" v-if="['草稿', '待审核'].includes(instockform.status)">删除</el-button>
                <el-button v-if="instockform.status === '待审核'" @click="ShowAudit">审核</el-button>
                <el-button v-if="['驳回'].includes(instockform.status)" type="warning" @click="ShowCancel">撤销</el-button>
                <el-button @click="showPrintDialog">打印</el-button>
            </div>
        </div>
        <hr style="border:1px solid #ccd0d4;"/>

        <div class="info-content">
             <table class="info-table">
                <tbody>
                    <tr>
                        <td>制单人</td>
                        <td>{{ instockform.createname }}</td>
                        <td>制单时间</td>
                        <td>{{ instockform.createtime }}</td>
                    </tr>
                    <tr>
                        <td>入库类型</td>
                        <td>{{ instockform.type }}</td>
                        <td>仓库</td>
                        <td>{{ instockform.whname }}</td>
                        <td>入库日期</td>
                        <td>{{ instockform.date }}</td>
                    </tr>
                    <tr>
                        <td>关联单号</td>
                        <td>{{ instockform.inorder }}</td>
                        <td>供应商</td>
                        <td>{{ instockform.supname }}</td>
                        <td>交货人</td>
                        <td>{{ instockform.linkname }}</td>
                    </tr>
                    <tr>
                        <td>联系方式</td>
                        <td>{{ instockform.linkphone }}</td>
                        <td>经办人</td>
                        <td>{{ instockform.inuser }}</td>
                        <td></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>备注</td>
                        <td>{{ instockform.remark }}</td>
                        <td>审核人</td>
                        <td>{{ instockform.auditname }}</td>
                        <td>审核时间</td>
                        <td>{{ instockform.audittime }}</td>
                    </tr>
                </tbody>
            </table>
            <div class="status-box">
                <div class="status-label">单据状态</div>
                <div class="status-value">{{ instockform.status }}</div>
            </div>
        </div>
    </div>

    <!--相关信息-->
    <div class="white-container">
        <el-tabs class="demo-tabs" style="margin-left: 20px;" v-model="activeTab">
            <el-tab-pane label="其他信息" name="first">
                <div style="text-align: left;">
                    <b style="font-size: 16px;">附件</b>
                    <div v-if="filelist.length === 0" style="color: #aaa; margin-top: 10px;">暂无附件</div>
                    <div v-else style="margin-top: 10px;">
                        <div v-for="(file, idx) in filelist" :key="idx" style="margin-bottom: 8px;">
                            <a :href="file.url" target="_blank" style="color: green; font-size: 15px; text-decoration: none;">
                            {{ file.name }}
                            </a>
                        </div>
                    </div>
                </div>
            </el-tab-pane>
            <el-tab-pane label="入库明细" name="second">
                <div style="text-align:left;">
                    <el-button @click="Export">导出</el-button>
                    <el-table :data="instockData" style="width: 100%" @selection-change="SelectChange">
                        <el-table-column type="selection" width="60"/>
                        <el-table-column type="index" label="序号" width="60"/>
                        <el-table-column prop="proc_name" label="货品名称" width="100"/>
                        <el-table-column prop="proc_code" label="货品编号" width="200" />
                        <el-table-column prop="proc_model" label="规格型号" />
                        <el-table-column prop="proc_primary_unit" label="单位" />
                        <el-table-column prop="type_name" label="货品类型" />
                        <el-table-column prop="slot_name" label="入库库位" />
                        <el-table-column prop="ind_num" label="入库数量" />
                        <el-table-column prop="ind_price" label="入库单价" width="120"/>
                        <el-table-column prop="ind_total" label="金额" width="120"/>
                        <el-table-column prop="remark" label="备注" width="200"/>
                    </el-table>
                    <div class="summary-row">
                        <span>合计</span>
                        <div>
                            <span class="summary-item">入库种类: <b style="color: #e6a23c;">{{ summary.totalItemTypes }}</b></span>
                            <span class="summary-item">入库数量: <b style="color: #e6a23c;">{{ summary.totalQuantity }}</b></span>
                            <span class="summary-item">总金额: <b style="color: #e6a23c;">{{ summary.totalAmount }}</b></span>
                        </div>
                    </div>
                </div>
            </el-tab-pane> 
        
        </el-tabs>
    </div>


    <!-- 底部操作栏 -->
    <div class="action-bar">
        <el-button @click="Close">关闭</el-button>
    </div>

    <!--删除模态框-->
    <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除该订单吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--撤销模态框-->
    <el-dialog v-model="CancelDialogVisible" width="400" style="text-align: left;" align-center>
        <span>确定撤销该订单吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="CancelDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Cancel">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--审核模态框-->
    <el-dialog v-model="AuditDialogVisible" width="400" style="text-align: left;" align-center>
        <el-form>
            <el-form-item label="审核结果">
                <el-radio-group v-model="auditResult">
                    <el-radio label="4">通过</el-radio>
                    <el-radio label="3">驳回</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="审核意见">
                <el-input v-model="auditComment" type="textarea" rows="3"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="AuditDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Audit()">确定</el-button>
            </div>
        </template>
    </el-dialog>

     <!--打印模态框-->
     <el-dialog v-model="printDialogVisible" width="500" >
            <div id="print-area" style="display: flex; align-items: center;">
                <div style="display: flex; flex-direction: column; align-items: center; margin-right: 20px;">
                    <QrcodeVue :value="instockform.code" :size="100" />
                    <span style="color: red; margin-top: 8px;">{{ instockform.code }}</span>
                </div>
                    <table border="1" style="border-collapse: collapse; width: 220px;">
                        <thead>
                            <tr>
                                <td>订单号</td>
                                <td>{{ instockform.code }}</td>
                            </tr>
                            <tr>
                                <td>供应商</td>
                                <td>{{ instockform.supname }}</td>
                            </tr>
                            <tr>
                                <td>交货人</td>
                                <td>{{ instockform.linkname }}</td>
                            </tr>
                        </thead>
                    </table>
            </div>
            <template #footer>
                <el-button class="no-print" @click="printDialogVisible = false">取消</el-button>
                <el-button class="no-print" type="primary" @click="handlePrint">打印</el-button>
            </template>
    </el-dialog>
</template>
  
<script>
import {ref,reactive,onMounted,computed} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox } from 'element-plus'; //提示信息
import { useRoute,useRouter  } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
    setup(){

        const route = useRoute();//路由（获取参数）
        const router = useRouter();//路由（实现跳转）
        //获取到传过来的instockid和instockcode
        const instockid=route.params.instockid;
        const instockcode=route.params.instockcode;
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));

        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //查询所有单据状态
        const status=ref([]);
        function GetStatus(){
            return http.get("/DictData/GetAllDictDataBytype?typeid=6")
            .then(res=>{
                status.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }
         // 状态映射计算属性
         const statusMap = computed(() => {
            const map = {};
            if (status.value && status.value.length > 0) {
                status.value.forEach(item => {
                    map[item.dict_value] = item.dict_label;
                });
            }
            return map;
        });

        //货品信息
        const instockform=reactive({
            code:instockcode,
            createname:"",
            createtime:"",
            depname:"",
            type:"",
            whid:"",
            whname:"",
            date:"",
            inorder:"",
            supname:"",
            linkname:"",
            linkphone:"",
            inuser:"",
            status:"",
            remark:"",
            auditname:"",
            audittime:"",
        })

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        //导出
        function Export(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "入库订单号": instockform.code,
                "货品名称": row.proc_name,
                "货品编号": row.proc_code,
                "规格型号": row.proc_model,
                "单位": row.proc_primary_unit,
                "货品类型": row.type_name,
                "入库库位": row.slot_name,
                "入库数量": row.ind_num,
                "入库单价": row.ind_price,
                "金额": row.ind_total,
                "备注": row.remark,
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "入库明细单");
            // 导出并下载
            XLSX.writeFile(wb, `入库明细单_${new Date().toLocaleDateString()}.xlsx`);
        }

        //附件
        const filelist = ref([])

        // 控制活动标签
        const activeTab = ref('second');

        //入库明细
        const instockData=ref([]);

        //合计计算
        const summary = computed(() => {
            if (!instockData.value || instockData.value.length === 0) {
                return {
                    totalItemTypes: 0,
                    totalQuantity: 0,
                    totalAmount: '0.00'
                };
            }

            const totalItemTypes = instockData.value.length;
            const totalQuantity = instockData.value.reduce((sum, item) => sum + Number(item.ind_num), 0);
            const totalAmount = instockData.value.reduce((sum, item) => sum + Number(item.ind_total), 0);

            return {
                totalItemTypes,
                totalQuantity,
                totalAmount: totalAmount.toFixed(2)
            };
        });

        //#region 查询对应信息
        function Select(){
            //查询入库单信息
            http.get("/Instock_h/GetInstock_hById?instockid="+instockid)
            .then(res=>{
                const data = res.data;
                instockform.createname=data.create_name;
                instockform.createtime=formatDateTime(new Date(data.create_time));
                instockform.date=formatDateTime(new Date(data.in_date));
                instockform.supname=data.sup_name;
                instockform.status=statusMap.value[data.in_status] || "未知状态";
                instockform.linkname=data.linkman; 
                instockform.remark=data.remark;
                instockform.type = data.in_type;
                instockform.whid = data.wh_id;
                instockform.whname = data.wh_name;
                instockform.inorder = data.in_order;
                instockform.linkphone = data.linkphone;
                instockform.inuser = data.in_user;
                instockform.auditname = data.approver_name;
                instockform.audittime = formatDateTime(new Date(data.approver_time));
            }).catch(err=>{
                console.log(err)
            })

            
            //查询货品附件
            http.get("/PublicFile/GetPublicFileBy?type=入库单&code="+instockcode)
            .then(res=>{
                filelist.value=res.data.map(item=>{
                    return {
                        name: item.title,
                        url:item.file_name
                    }
                })
            })

            //查询明细信息
            http.get("/Instock_d/GetInstock_Ds?instockid="+instockid)
            .then(res => {
                const instocklist = res.data;
                if (!instocklist || instocklist.length === 0) return;

                const promises = instocklist.map(detail =>
                    http.get("/Product/GetProductById?id=" + detail.proc_id).then(productRes => ({
                        ...detail,
                        proc_name: productRes.data.proc_name,
                        proc_code: productRes.data.proc_code,
                        proc_model: productRes.data.proc_model,
                        proc_primary_unit: productRes.data.proc_primary_unit,
                        type_name: productRes.data.type_name,
                    }))
                );

                Promise.all(promises)
                    .then(completedItems => {
                        instockData.value = completedItems.map(item => ({
                            ...item,
                            ind_price: parseFloat(item.ind_price).toFixed(2),
                            ind_total: parseFloat(item.ind_total).toFixed(2),
                        }));
                    })
                    .catch(err => {
                        console.error(err);
                    });
            }).catch(err => {
                console.log(err);
            });
        }
        //#endregion


        //关闭
        function Close(){
            router.back();
        }


        //#region 跳转修改页面

         function ShowUpdate(){
            //传当前对应货品Id过去
            router.push({
                name:"instockupdate",
                params:{
                    instockid:instockid,
                    instockcode:instockcode,
                }
            })
        }
        //#endregion


        //#region 删除

            //删除模态框
            const DeleteialogVisible=ref(false);
            //删除模态框
            function ShowDelete(){
                DeleteialogVisible.value=true;
            }
            async function Delete(){
                try {
                    // 直接调用删除接口
                    const deleteRes = await http.put("/Instock_h/DeleteInstock_h?id=" + instockid);
                    if (deleteRes.data > 0) {
                        ElMessage({ message: '删除成功.', type: 'success' });
                        DeleteialogVisible.value = false;
                        router.push({name:"instock"});
                    } else {
                        ElMessage.error('删除失败.');
                    }
                } catch (err) {
                    console.error("删除失败:", err);
                    ElMessage.error('删除操作失败.');
                }
            }

        //#endregion

        //#region 审核
        //审核模态框
        const AuditDialogVisible=ref(false);
        const auditResult=ref("3"); // 默认通过
        const auditComment=ref("");

        function ShowAudit(){
            AuditDialogVisible.value = true;
        }

        async function Audit(){
            try {
                // 审核前检查仓库是否锁定
                if (instockform.whid) {
                    const warehouseRes = await http.get(`/Warehouse/GetIdWarehouse?id=${instockform.whid}`);
                    if (warehouseRes.data && warehouseRes.data.is_lock === 1) {
                        ElMessage.error(`该仓库已被锁定，不能进行审核操作！`);
                        return;
                    }
                }

                // 仓库未锁定，执行审核
                const res = await http.put("/Instock_h/ApproverInstock_h?instockid="+instockid+"&status="+auditResult.value+"&approvername="+user.name+"&approvertime="+formatDateTime(new Date()));
                
                if(res.data>0){
                    ElMessage.success('审核成功');
                    Select();
                    AuditDialogVisible.value=false;
                }else{
                    ElMessage.error('审核失败');
                }
            } catch (error) {
                console.error("审核失败:", error);
                if (error.response?.status === 400) {
                    ElMessage.error('仓库状态验证失败，请稍后再试');
                } else {
                    ElMessage.error('审核操作失败');
                }
            }
        }
        //#endregion

        //#region 撤销
        //撤销模态框
        const CancelDialogVisible=ref(false);

        function ShowCancel(){
            CancelDialogVisible.value = true;
        }

        function Cancel(){
            http.put("/Instock_h/UpdateStatus?instockid="+instockid+"&status=2")
            .then(res=>{
                if(res.data>0){
                    ElMessage({
                        message: '撤销成功.',
                        type: 'success',
                    })
                    Select();
                    CancelDialogVisible.value=false;
                }else{
                    ElMessage.error('撤销失败.')
                }
            }).catch(err=>{
                console.log(err);
            })
        }
        //#endregion

        //#region 打印
        const printDialogVisible = ref(false);
        function showPrintDialog() {
            printDialogVisible.value = true;
        }
        function handlePrint() {
            window.print();
        }
        //#endregion


        //挂载
        onMounted(() => {
           GetStatus().then(()=>{
            Select();
           })
        });

        return{
            Close,
            filelist,
            user,
            instockform,
            formatDateTime,
            activeTab,
            ShowUpdate,
            DeleteialogVisible,
            ShowDelete,
            Delete,
            printDialogVisible,
            showPrintDialog,
            handlePrint,
            statusMap,
            AuditDialogVisible,
            auditResult,
            auditComment,
            ShowAudit,
            Audit,
            CancelDialogVisible,
            ShowCancel,
            Cancel,
            instockData,
            summary,
            SelectChange,
            selectdata,
            Export
        }
    }
}
</script>
  
<style scoped>
    /* 白色圆角容器 - 核心样式 */
    .white-container {
        background: white;
        border-radius: 12px;
        margin-bottom: 50px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
        width: 75%;
    }

    /* 底部操作栏自适应 */
    .action-bar {
        position: fixed;
        bottom: 0;
        right: 0.5%; /* 与表单右侧对齐 */
        left: 210px; /* 与菜单栏宽度一致 */
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;
        text-align: right;
    }

    .header-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20px 20px 0 20px;
    }

    .title {
        margin: 0;
        font-size: 20px;
        font-weight: bold;
    }

    .btn-group > .el-button {
        margin-left: 10px;
    }

    .stock-bar {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        gap: 80px; /* 两列间距可调整 */
        margin: 20px 0;
    }

    .stock-item {
        text-align: center;
    }

    .stock-value {
        font-size: 22px;
        font-weight: bold;
        color: #222;
    }

    .stock-label {
        color: #888;
        font-size: 14px;
        margin-top: 4px;
    }
    .info-main-row {
        display: flex;
        flex-direction: row;
        align-items: flex-start; /* 顶部对齐 */
        gap: 30px; /* 左右间距，可根据需要调整 */
    }

    /* 新增表格样式 */
    .info-content {
        padding: 20px;
        position: relative;
    }
    
    .info-table {
        width: 100%;
        border-collapse: collapse;
        text-align: left;
    }
    
    .info-table td {
        padding: 10px 15px;
        font-size: 14px;
        color: #606266;
    }
    
    .info-table td:nth-child(odd) {
        width: 80px;
        color: #303133;
        font-weight: 500;
    }
    
    .status-box {
        position: absolute;
        top: 20px;
        right: 30px;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    
    .status-label {
        font-size: 14px;
        margin-bottom: 10px;
    }
    
    .status-value {
        font-size: 16px;
        font-weight: bold;
        color: #e6a23c;
    }

    .summary-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 20px;
        font-size: 14px;
    }

    .summary-row > span {
        font-weight: bold;
    }

    .summary-item {
        margin-left: 25px;
        color: #606266;
    }

    .summary-item > span {
        font-weight: bold;
    }

    @media print {
        .no-print {
            display: none !important;
        }
    }
</style>
